import tkinter as tk
import random


class SnakeGame:
    def __init__(self, master):
        self.master = master
        self.master.title("贪吃蛇")
        self.master.resizable(False, False)

        # 游戏参数
        self.cell_size = 20
        self.width = 30
        self.height = 20
        self.delay = 150

        # 初始化界面
        self.canvas = tk.Canvas(
            master,
            width=self.width * self.cell_size,
            height=self.height * self.cell_size,
            bg="black",
        )
        self.canvas.pack()

        # 游戏状态
        self.snake = [(10, 10), (10, 9), (10, 8)]
        self.direction = "Right"
        self.food = self.create_food()
        self.score = 0
        self.game_over = False

        # 绑定键盘事件
        self.master.bind("<Key>", self.change_direction)

        # 开始游戏
        self.update()

    def create_food(self):
        while True:
            x = random.randint(0, self.width - 1)
            y = random.randint(0, self.height - 1)
            if (x, y) not in self.snake:
                return (x, y)

    def change_direction(self, event):
        key = event.keysym
        if key in ["Up", "Down", "Left", "Right"]:
            if (
                key == "Up"
                and self.direction != "Down"
                or key == "Down"
                and self.direction != "Up"
                or key == "Left"
                and self.direction != "Right"
                or key == "Right"
                and self.direction != "Left"
            ):
                self.direction = key

    def update(self):
        if self.game_over:
            return

        # 移动蛇
        head_x, head_y = self.snake[0]
        if self.direction == "Up":
            new_head = (head_x, head_y - 1)
        elif self.direction == "Down":
            new_head = (head_x, head_y + 1)
        elif self.direction == "Left":
            new_head = (head_x - 1, head_y)
        elif self.direction == "Right":
            new_head = (head_x + 1, head_y)

        # 碰撞检测
        if (
            new_head in self.snake
            or new_head[0] < 0
            or new_head[0] >= self.width
            or new_head[1] < 0
            or new_head[1] >= self.height
        ):
            self.game_over = True
            self.canvas.create_text(
                self.width * self.cell_size / 2,
                self.height * self.cell_size / 2,
                text=f"游戏结束! 得分: {self.score}",
                fill="white",
                font=("Arial", 20),
            )
            return

        self.snake.insert(0, new_head)

        # 吃到食物
        if new_head == self.food:
            self.score += 10
            self.food = self.create_food()
        else:
            self.snake.pop()

        # 重绘画面
        self.canvas.delete("all")
        for x, y in self.snake:
            self.canvas.create_rectangle(
                x * self.cell_size,
                y * self.cell_size,
                (x + 1) * self.cell_size,
                (y + 1) * self.cell_size,
                fill="green",
            )

        # 绘制食物
        food_x, food_y = self.food
        self.canvas.create_oval(
            food_x * self.cell_size,
            food_y * self.cell_size,
            (food_x + 1) * self.cell_size,
            (food_y + 1) * self.cell_size,
            fill="red",
        )

        # 显示分数
        self.canvas.create_text(
            30, 10, text=f"得分: {self.score}", fill="white", anchor="w"
        )

        self.master.after(self.delay, self.update)


if __name__ == "__main__":
    root = tk.Tk()
    game = SnakeGame(root)
    root.mainloop()
